package com.company.aicrawlers.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web配置类
 *
 * @author AI Crawlers Team
 * @date 2025-10-10
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    /**
     * 静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 映射静态资源（不覆盖默认配置）
        registry.addResourceHandler("/assets/**")
                .addResourceLocations("classpath:/static/assets/");
        
        registry.addResourceHandler("/pages/**")
                .addResourceLocations("classpath:/static/pages/");
                
        registry.addResourceHandler("/extension/**")
                .addResourceLocations("classpath:/static/extension/");
        
        // 映射根路径静态资源（包括 index.html）
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");
    }
    
    /**
     * 默认首页
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 访问根路径自动显示 index.html
        registry.addViewController("/").setViewName("forward:/index.html");
    }
    
    /**
     * CORS跨域配置
     * 支持浏览器插件从AI平台页面跨域请求后端API
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")  // 所有API接口
                .allowedOriginPatterns("*")  // 允许所有来源（开发环境）
                // 生产环境建议指定具体域名：
                // .allowedOrigins(
                //     "https://chat.deepseek.com",
                //     "https://yuanbao.tencent.com", 
                //     "https://doubao.com"
                // )
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);  // 预检请求缓存1小时
    }
}

